import { Validator, ValidatorFn, AbstractControl, ValidationErrors, NG_VALIDATORS } from '@angular/forms';
import { Directive, Input, OnChanges, SimpleChanges, StaticProvider, forwardRef } from '@angular/core';

/**
 * 相同验证
 * 密码确认验证
 * 
 * @param name control name
 */
export function equal(name: string): ValidatorFn {
  return (control: AbstractControl): ValidationErrors | null => {
    if (control.value == null || control.value.length == 0) {
      return null;
    }
    let v = control.value;
    let e = control.root.get(name);

    if (e && v !== e.value) {
      return { equal: true, error: true };
    }

    return null;
  };
}

@Directive({
  selector: '[equal][formControlName],[equal][formControl],[equal][ngModel]',
  providers: [{
    provide: NG_VALIDATORS,
    useExisting: forwardRef(() => EqualValidator),
    multi: true
  }]
})
export class EqualValidator implements Validator, OnChanges {
  private _validator: ValidatorFn;
  private _onChange: () => void;

  @Input('equal') equal: string;

  ngOnChanges(changes: SimpleChanges): void {
    if ('equal' in changes) {
      this._createValidator();
      if (this._onChange) this._onChange();
    }
  }

  validate(c: AbstractControl): ValidationErrors | null { return this._validator(c); }

  registerOnValidatorChange(fn: () => void): void { this._onChange = fn; }

  private _createValidator(): void { this._validator = equal(this.equal); }
}